package cn.iocoder.yudao.module.project.controller.admin.weighthistory;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.module.project.dal.dataobject.internalcode.InternalCodeDO;
import cn.iocoder.yudao.module.project.dal.mysql.internalcode.InternalCodeMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.time.LocalDate;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.project.controller.admin.weighthistory.vo.*;
import cn.iocoder.yudao.module.project.dal.dataobject.weighthistory.WeightHistoryDO;
import cn.iocoder.yudao.module.project.service.weighthistory.WeightHistoryService;

@Tag(name = "管理后台 - 称重业务")
@RestController
@RequestMapping("/project/weight-history")
@Validated
public class WeightHistoryController {

    @Resource
    private WeightHistoryService weightHistoryService;

    @Resource
    private InternalCodeMapper internalCodeMapper;

    @PostMapping("/create")
    @Operation(summary = "创建称重业务")
    // @PreAuthorize("@ss.hasPermission('project:weight-history:create')")
    public CommonResult<String> createWeightHistory(@Valid @RequestBody WeightHistorySaveReqVO createReqVO) {
        return success(weightHistoryService.createWeightHistory(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新称重业务")
    // @PreAuthorize("@ss.hasPermission('project:weight-history:update')")
    public CommonResult<Boolean> updateWeightHistory(@Valid @RequestBody WeightHistorySaveReqVO updateReqVO) {
        weightHistoryService.updateWeightHistory(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除称重业务")
    @Parameter(name = "id", description = "编号", required = true)
    // @PreAuthorize("@ss.hasPermission('project:weight-history:delete')")
    public CommonResult<Boolean> deleteWeightHistory(@RequestParam("id") String id) {
        weightHistoryService.deleteWeightHistory(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得称重业务")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    // @PreAuthorize("@ss.hasPermission('project:weight-history:query')")
    public CommonResult<WeightHistoryRespVO> getWeightHistory(@RequestParam("id") String id) {
        WeightHistoryDO weightHistory = weightHistoryService.getWeightHistory(id);
        return success(BeanUtils.toBean(weightHistory, WeightHistoryRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得称重业务分页")
    // @PreAuthorize("@ss.hasPermission('project:weight-history:query')")
    public CommonResult<PageResult<WeightHistoryRespVO>> getWeightHistoryPage(@Valid WeightHistoryPageReqVO pageReqVO) {
        PageResult<WeightHistoryDO> pageResult = weightHistoryService.getWeightHistoryPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, WeightHistoryRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出称重业务 Excel")
    // @PreAuthorize("@ss.hasPermission('project:weight-history:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportWeightHistoryExcel(@Valid WeightHistoryPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<WeightHistoryDO> list = weightHistoryService.getWeightHistoryPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "称重业务.xls", "数据", WeightHistoryRespVO.class,
                        BeanUtils.toBean(list, WeightHistoryRespVO.class));
    }




    @RequestMapping("/weightHistory")
    @Operation(summary = "称重报表")
    // @PreAuthorize("@ss.hasPermission('project:production-code:create')")
    public CommonResult<PageResult<WeightHistoryReportVO>> selectMaterialReceipt(@RequestBody WeightHistoryPageReqVO pageReqVO) {
        Map<String, Object> params = new HashMap<>();
        params.put("pageNo", (pageReqVO.getPageNo() - 1) * pageReqVO.getPageSize());
        params.put("pageSize", pageReqVO.getPageSize());

        String type = pageReqVO.getType();
        if (StringUtils.isNotBlank(type)) {
            params.put("type", type);
        }

        String internalCode = pageReqVO.getInternalCode();
        if (StringUtils.isNotBlank(internalCode)) {
            params.put("internalCode", internalCode);
        }

        String orderCode = pageReqVO.getOrderCode();
        if (StringUtils.isNotBlank(orderCode)) {
            params.put("orderCode", orderCode);
        }

        Long scaleId = pageReqVO.getScaleId();
        if (null != scaleId) {
            params.put("scaleId", scaleId);
        }

        String scaleName = pageReqVO.getScaleName();
        if (StringUtils.isNotBlank(scaleName)) {
            params.put("scaleName", scaleName);
        }

        String flex = pageReqVO.getFlex();
        if(StringUtils.isNotBlank(flex)){
            params.put("flex", flex);
        }

        Integer len = pageReqVO.getLen();
        if(null != len){
            params.put("len", len);
        }

        String[] dateReq = pageReqVO.getDateReq();
        if (null != dateReq && dateReq.length == 2) {
            String startTime = dateReq[0];
            String endTime = dateReq[1];
            if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
                LocalDate startDate = LocalDate.parse(startTime);
                LocalDate endDate = LocalDate.parse(endTime);
                params.put("startDate", startDate);
                params.put("endDate", endDate);
            }
        }
        List<WeightHistoryReportVO> dataList = weightHistoryService.selectWeightHistory(params);
        Long count = weightHistoryService.countWeightHistory(params);

        // 设置订单号和规格型号
        if (CollectionUtil.isNotEmpty(dataList)) {
            List<String> internalCodeList = dataList.stream()
                    .map(c -> c.getInternalCode())
                    .collect(Collectors.toList());

            QueryWrapper<InternalCodeDO> internalCodeDOQueryWrapper = new QueryWrapper<>();
            internalCodeDOQueryWrapper.in("id", internalCodeList);
            List<InternalCodeDO> internalCodeDOS = internalCodeMapper.selectList(internalCodeDOQueryWrapper);
            if (CollectionUtil.isNotEmpty(internalCodeDOS)) {
                for (WeightHistoryReportVO weightHistoryReportVO : dataList) {
                    for (InternalCodeDO internalCodeDO : internalCodeDOS) {
                        if (StringUtils.equals(weightHistoryReportVO.getInternalCode(), internalCodeDO.getId())) {
                            String orderCode1 = internalCodeDO.getOrderCode();
                            String type1 = internalCodeDO.getType();
                            weightHistoryReportVO.setOrderCode(orderCode1);
                            weightHistoryReportVO.setType(type1);
                        }
                    }
                }
            }
        }

        PageResult<WeightHistoryReportVO> pageResult = new PageResult<>();
        pageResult.setList(dataList);
        pageResult.setTotal(count);
        return success(pageResult);
    }

}